<template>
  <div class="cloud-model-config">
    <a-alert
      message="云端大模型配置"
      description="配置阿里云百炼等云端大模型服务，包括聊天、视觉分析和实时音频功能。"
      type="info"
      show-icon
      closable
      style="margin-bottom: 16px"
    />

    <!-- 总开关 -->
    <a-card title="总开关" :bordered="false" style="margin-bottom: 24px">
      <div class="switch-container">
        <a-switch
          v-model:checked="configData.enabled"
          @change="handleEnabledChange"
          :loading="saving"
        />
        <span class="switch-label">启用云端大模型服务</span>
      </div>
    </a-card>

    <!-- 功能配置 -->
    <a-card title="功能配置" :bordered="false" style="margin-bottom: 24px">
      <a-form
        :model="configData"
        layout="vertical"
        :disabled="!configData.enabled || saving"
      >
        <a-row :gutter="24">
          <!-- 聊天功能 -->
          <a-col :span="8">
            <a-card size="small" title="聊天功能" :bordered="true">
              <a-form-item label="服务厂商">
                <a-select
                  v-model:value="configData.chat.provider"
                  @change="handleProviderChange('chat')"
                  style="width: 100%"
                >
                  <a-select-option value="aliyun">阿里云</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="模型">
                <a-select
                  v-model:value="configData.chat.model"
                  style="width: 100%"
                >
                  <a-select-option value="qwen-plus">Qwen Plus</a-select-option>
                  <a-select-option value="qwen-turbo">Qwen Turbo</a-select-option>
                  <a-select-option value="qwen-max">Qwen Max</a-select-option>
                </a-select>
              </a-form-item>
            </a-card>
          </a-col>

          <!-- 视觉功能 -->
          <a-col :span="8">
            <a-card size="small" title="视觉分析功能" :bordered="true">
              <a-form-item label="服务厂商">
                <a-select
                  v-model:value="configData.vision.provider"
                  @change="handleProviderChange('vision')"
                  style="width: 100%"
                >
                  <a-select-option value="aliyun">阿里云</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="模型">
                <a-select
                  v-model:value="configData.vision.model"
                  style="width: 100%"
                >
                  <a-select-option value="qwen-vl-plus">Qwen VL Plus</a-select-option>
                  <a-select-option value="qwen-vl-max">Qwen VL Max</a-select-option>
                </a-select>
              </a-form-item>
            </a-card>
          </a-col>

          <!-- 实时音频 -->
          <a-col :span="8">
            <a-card size="small" title="实时音频功能" :bordered="true">
              <a-form-item label="服务厂商">
                <a-select
                  v-model:value="configData.realtime_audio.provider"
                  @change="handleProviderChange('realtime_audio')"
                  style="width: 100%"
                >
                  <a-select-option value="aliyun">阿里云</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="模型">
                <a-select
                  v-model:value="configData.realtime_audio.model"
                  style="width: 100%"
                >
                  <a-select-option value="qwen3-omni-flash-realtime">Qwen3 Omni Flash Realtime</a-select-option>
                </a-select>
              </a-form-item>
              <a-form-item label="交互模式">
                <a-select
                  v-model:value="configData.realtime_audio.mode"
                  style="width: 100%"
                >
                  <a-select-option value="vad">语音活动检测（自动触发）</a-select-option>
                  <a-select-option value="manual">手动控制</a-select-option>
                </a-select>
              </a-form-item>
            </a-card>
          </a-col>
        </a-row>
      </a-form>
    </a-card>

    <!-- 厂商配置 -->
    <a-card title="厂商配置" :bordered="false" style="margin-bottom: 24px">
      <a-form
        :model="configData"
        layout="vertical"
        :disabled="!configData.enabled || saving"
      >
        <a-tabs v-model:activeKey="activeProviderTab">
          <a-tab-pane key="aliyun" tab="阿里云">
            <a-row :gutter="24">
              <a-col :span="12">
                <a-form-item
                  label="API Key"
                  required
                  :validateStatus="apiKeyValidation.status"
                  :help="apiKeyValidation.message"
                >
                  <a-input-password
                    v-model:value="configData.providers.aliyun.api_key"
                    placeholder="请输入阿里云API Key"
                    @change="handleApiKeyChange"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="12">
                <a-form-item label="操作">
                  <a-space>
                    <a-button type="primary" @click="testConnection" :loading="testing">
                      <template #icon><api-outlined /></template>
                      测试连接
                    </a-button>
                    <a-tooltip title="如何获取API Key">
                      <a-button type="link" @click="showApiKeyHelp">
                        <template #icon><question-circle-outlined /></template>
                        获取帮助
                      </a-button>
                    </a-tooltip>
                  </a-space>
                </a-form-item>
              </a-col>
            </a-row>
          </a-tab-pane>
        </a-tabs>
      </a-form>
    </a-card>

    <!-- 操作按钮 -->
    <div class="action-buttons">
      <a-space>
        <a-button type="primary" @click="saveConfig" :loading="saving">
          <template #icon><save-outlined /></template>
          保存配置
        </a-button>
        <a-button @click="resetConfig" :disabled="saving">
          <template #icon><reload-outlined /></template>
          重置
        </a-button>
        <a-button @click="refreshConfig" :loading="loading">
          <template #icon><sync-outlined /></template>
          刷新
        </a-button>
      </a-space>
    </div>

    <!-- API Key帮助对话框 -->
    <a-modal
      v-model:visible="helpModalVisible"
      title="如何获取阿里云API Key"
      :footer="null"
      width="600px"
    >
      <a-steps direction="vertical" size="small">
        <a-step title="登录阿里云控制台" description="访问 https://bailian.console.aliyun.com/" />
        <a-step title="开通百炼服务" description="在控制台中开通阿里云百炼服务" />
        <a-step title="创建API Key" description="在 AccessKey管理页面创建新的API Key" />
        <a-step title="配置权限" description="为API Key配置百炼服务相关权限" />
        <a-step title="复制API Key" description="复制生成的API Key到本配置页面" />
      </a-steps>
      <div style="margin-top: 16px; text-align: center;">
        <a-button type="primary" href="https://bailian.console.aliyun.com/" target="_blank">
          <template #icon><link-outlined /></template>
          前往阿里云控制台
        </a-button>
      </div>
    </a-modal>
  </div>
</template>

<script>
import { defineComponent, ref, onMounted, computed, reactive } from 'vue';
import { message } from 'ant-design-vue';
import {
  SaveOutlined,
  ReloadOutlined,
  SyncOutlined,
  ApiOutlined,
  QuestionCircleOutlined,
  LinkOutlined
} from '@ant-design/icons-vue';
import { getCloudModelConfig, setCloudModelConfig } from '../../api/config';

export default defineComponent({
  name: 'CloudModelConfig',
  components: {
    SaveOutlined,
    ReloadOutlined,
    SyncOutlined,
    ApiOutlined,
    QuestionCircleOutlined,
    LinkOutlined
  },
  setup() {
    // 状态管理
    const loading = ref(false);
    const saving = ref(false);
    const testing = ref(false);
    const helpModalVisible = ref(false);
    const activeProviderTab = ref('aliyun');

    // 配置数据
    const configData = ref({
      enabled: true,
      chat: {
        provider: 'aliyun',
        model: 'qwen-plus'
      },
      vision: {
        provider: 'aliyun',
        model: 'qwen-vl-plus'
      },
      realtime_audio: {
        provider: 'aliyun',
        model: 'qwen3-omni-flash-realtime',
        mode: 'vad'
      },
      providers: {
        aliyun: {
          api_key: ''
        }
      }
    });

    // API Key验证
    const apiKeyValidation = reactive({
      status: '',
      message: ''
    });

    // 验证API Key
    const validateApiKey = (apiKey) => {
      if (!apiKey || apiKey.trim() === '') {
        apiKeyValidation.status = 'error';
        apiKeyValidation.message = 'API Key不能为空';
        return false;
      }
      if (apiKey.length < 10) {
        apiKeyValidation.status = 'error';
        apiKeyValidation.message = 'API Key格式不正确';
        return false;
      }
      apiKeyValidation.status = 'success';
      apiKeyValidation.message = '';
      return true;
    };

    // 处理API Key变化
    const handleApiKeyChange = () => {
      const apiKey = configData.value.providers.aliyun.api_key;
      validateApiKey(apiKey);
    };

    // 处理总开关变化
    const handleEnabledChange = (enabled) => {
      if (!enabled) {
        // 关闭时清空验证状态
        apiKeyValidation.status = '';
        apiKeyValidation.message = '';
      }
    };

    // 处理厂商变化
    const handleProviderChange = (feature) => {
      // 当厂商变化时，可以设置默认模型
      const provider = configData.value[feature].provider;
      console.log(`${feature} provider changed to: ${provider}`);
    };

    // 加载配置
    const loadConfig = async () => {
      try {
        loading.value = true;
        const config = await getCloudModelConfig();

        if (config) {
          // 合并配置数据，保留默认值
          configData.value = {
            ...configData.value,
            ...config,
            providers: {
              ...configData.value.providers,
              ...config.providers
            }
          };
        }

        // 验证当前的API Key
        if (configData.value.providers.aliyun.api_key) {
          validateApiKey(configData.value.providers.aliyun.api_key);
        }

        message.success('配置加载成功');
      } catch (error) {
        console.error('加载云端大模型配置失败:', error);
        message.error('加载配置失败: ' + (error.message || '未知错误'));
      } finally {
        loading.value = false;
      }
    };

    // 保存配置
    const saveConfig = async () => {
      if (!configData.value.enabled) {
        // 如果未启用，直接保存
        await doSaveConfig();
        return;
      }

      // 验证API Key
      const apiKey = configData.value.providers.aliyun.api_key;
      if (!validateApiKey(apiKey)) {
        message.error('请正确配置API Key');
        return;
      }

      await doSaveConfig();
    };

    // 执行保存配置
    const doSaveConfig = async () => {
      try {
        saving.value = true;
        await setCloudModelConfig(configData.value);
        message.success('配置保存成功');
      } catch (error) {
        console.error('保存云端大模型配置失败:', error);
        message.error('保存配置失败: ' + (error.message || '未知错误'));
      } finally {
        saving.value = false;
      }
    };

    // 重置配置
    const resetConfig = () => {
      // 重置到默认值
      configData.value = {
        enabled: true,
        chat: {
          provider: 'aliyun',
          model: 'qwen-plus'
        },
        vision: {
          provider: 'aliyun',
          model: 'qwen-vl-plus'
        },
        realtime_audio: {
          provider: 'aliyun',
          model: 'qwen3-omni-flash-realtime',
          mode: 'vad'
        },
        providers: {
          aliyun: {
            api_key: ''
          }
        }
      };

      // 清空验证状态
      apiKeyValidation.status = '';
      apiKeyValidation.message = '';

      message.info('配置已重置为默认值');
    };

    // 刷新配置
    const refreshConfig = () => {
      loadConfig();
    };

    // 测试连接
    const testConnection = async () => {
      const apiKey = configData.value.providers.aliyun.api_key;
      if (!validateApiKey(apiKey)) {
        message.error('请先配置正确的API Key');
        return;
      }

      try {
        testing.value = true;

        // 这里应该调用实际的测试连接API
        // 暂时模拟测试过程
        await new Promise(resolve => setTimeout(resolve, 2000));

        message.success('连接测试成功');
      } catch (error) {
        console.error('连接测试失败:', error);
        message.error('连接测试失败: ' + (error.message || '未知错误'));
      } finally {
        testing.value = false;
      }
    };

    // 显示API Key帮助
    const showApiKeyHelp = () => {
      helpModalVisible.value = true;
    };

    // 组件挂载时加载配置
    onMounted(() => {
      loadConfig();
    });

    return {
      loading,
      saving,
      testing,
      helpModalVisible,
      activeProviderTab,
      configData,
      apiKeyValidation,
      loadConfig,
      saveConfig,
      resetConfig,
      refreshConfig,
      testConnection,
      showApiKeyHelp,
      handleEnabledChange,
      handleProviderChange,
      handleApiKeyChange
    };
  }
});
</script>

<style scoped>
.cloud-model-config {
  padding: 24px;
}

.switch-container {
  display: flex;
  align-items: center;
  gap: 12px;
}

.switch-label {
  font-size: 14px;
  color: rgba(0, 0, 0, 0.65);
}

.action-buttons {
  text-align: center;
  padding: 24px 0;
}

:deep(.ant-card-head-title) {
  font-weight: 600;
}

:deep(.ant-form-item-label > label) {
  font-weight: 500;
}

:deep(.ant-select-selector) {
  border-radius: 6px;
}

:deep(.ant-input) {
  border-radius: 6px;
}

:deep(.ant-tabs-content-holder) {
  padding-top: 16px;
}

:deep(.ant-steps-item-description) {
  color: rgba(0, 0, 0, 0.65);
}
</style>